import Vue from 'vue';
import axios from 'axios';
import store from '@/store';
import { openNotification } from './util';
import { VueAxios } from './axios';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { Loading } from 'element-ui'

// 创建 axios 实例
const service = axios.create({
    baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
    timeout: 0 // 请求超时时间
});
let loadingInstance = null

const err = error => {
    if (error.response) {
        const data = error.response.data;
        const token = Vue.ls.get(ACCESS_TOKEN);
        if (error.response.status === 403) {
            openNotification('error', 'Forbidden', data.message);
        }
        if (error.response.status === 500) {
            openNotification('error', '后台500错误', '联系后台检查服务');
        }
        if (error.response.status === 404) {
            openNotification('error', '接口404错误', '请检查请求url');
        }
        if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
            openNotification('error', '提示', '认证过期即将跳转登录页');
            store.dispatch('Logout', true).then(() => {
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            });
        }
    }
    return Promise.reject(error);
};

// request interceptor
service.interceptors.request.use(config => {
    const loadingWhite = ['/notify/info/noticeCount'] // 整页加载框的白名单，即名单中的接口不需要显示加载框
    if (loadingWhite.indexOf(config.url) < 0) {
        const options = {
            background: 'rgba(0, 0, 0, 0.1)',
            // background: 'transparent'
        }
        loadingInstance = Loading.service(options) // 整页加载框
    }

    // 是否在拦截错误信息后，弹出统一提示错误（默认为true）
    config.interceptorErr = config.interceptorErr === false ? false : true
    const token = Vue.ls.get(ACCESS_TOKEN);
    // console.log('token=======', token)
    if (token) {
        config.headers['token'] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    return config;
}, err);

// response interceptor
service.interceptors.response.use(response => {
    if (loadingInstance) {
        loadingInstance.close()
    }
    try {
        const { data } = response;
        if (data.state) {
            if (data.state === '000000') {
                return {
                    ...data,
                    headers: response.headers
                }
            } else { 
                if (data.state === '100005') {
                    openNotification('error', '认证过期即将跳转登录页');
                    store.dispatch('Logout', true).then(() => {
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    });
                } else {
                    if (response.config.interceptorErr) { // 是否拦截错误
                        openNotification('error', '请求错误', data.message);
                    }
                }
                return Promise.reject(new Error((data && data.message) || 'Error'))
            }
        } else {
            const url = response.config.url
            if (url && url.indexOf('/ureport') >= 0) { // ureport打印接口需单独处理
                return data
            }
        }
    } catch (error) {
        openNotification('error', '未知错误请刷新页面重试');
        return Promise.reject(new Error('未知错误请刷新页面重试'))
    }
}, err);

const installer = {
    vm: {},
    install(Vue) {
        Vue.use(VueAxios, service);
    }
};

export { installer as VueAxios, service as axios };
